#include "Projectile.h"
#include "Map.h"

Projectile::Projectile()
	: mActive(false) //why is this better?
{
}

Projectile::~Projectile()
{
}

void Projectile::Load(const char* projName)
{
	if(projName == "denture")
	{
		mSprite.Add("dentureopen.png");
		mSprite.Add("dentureclosed.png");
	}
	else if(projName == "taco")
		mSprite.Load("tacoprojectile.png");
}

void Projectile::Unload()
{
	mSprite.Unload();
}

void Projectile::Update(float deltaTime, Map& map)
{
	if(mActive)
	{
		mSprite.Update(deltaTime);
		mPosition += mVelocity * deltaTime;

		EnvironmentCollision(map);
	}
}

void Projectile::Render(const SVector2& viewOffset)
{
	if(mActive)
	{
		int width = mSprite.GetWidth();
		int height = mSprite.GetHeight();

		SVector2 offset(width * 0.5f, height * 0.5f);
		SVector2 renderPosition = mPosition - offset - viewOffset;

		mSprite.SetPosition(renderPosition);
		if(mVelocity.x < 0.0f)
			mSprite.SetFlipH(true);
		else if(mVelocity.x >= 0.0f)
			mSprite.SetFlipH(false);
		mSprite.Render();
		//Graphics_DebugCircle(renderPosition, 10.0f, 0x00ff00);
	}
}

void Projectile::Fire(const SVector2& pos, const SVector2& vel)
{
	mPosition = pos;
	mVelocity = vel;
	mActive = true;
	mSprite.Play(3.0f, true);
}

void Projectile::Kill()
{
	//set false to stop update and render functions
	mActive = false;
	mSprite.Stop();
	mSprite.Reset();
}

SRect Projectile::GetBoundingBox() const
{
	SRect boundingBox;
	
	//using magic numbers containing size of content on sprite
	boundingBox.min.x = mPosition.x - 10.0f;
	boundingBox.max.x = mPosition.x + 10.0f;
	boundingBox.min.y = mPosition.y - 10.0f;
	boundingBox.max.y = mPosition.y + 10.0f;

	return boundingBox;
}

void Projectile::EnvironmentCollision(Map& map)
{
	SRect boundingBox = GetBoundingBox();
	if(mVelocity.y >= 0)
	{
		SLineSegment segment = boundingBox.GetBottomSegment();
		SRect collisionBox;
		if(map.TestCollision(segment, collisionBox))
			Kill();
	}
	else if(mVelocity.y < 0)
	{
		SLineSegment segment = boundingBox.GetTopSegment();
		SRect collisionBox;
		if(map.TestCollision(segment, collisionBox))
			Kill();
	}

	if(mVelocity.x >= 0)
	{
		SLineSegment segment = boundingBox.GetRightSegment();
		SRect collisionBox;
		if(map.TestCollision(segment, collisionBox))
			Kill();
	}
	else if(mVelocity.x < 0)
	{
		SLineSegment segment = boundingBox.GetLeftSegment();
		SRect collisionBox;
		if(map.TestCollision(segment, collisionBox))
			Kill();
	}
}